from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
from educate_ai.database import get_db
from educate_ai.questions_part import schema
from educate_ai.questions_part import crud

app = APIRouter(prefix="/questions", tags=["questions"])

@app.post("/", response_model=schema.QuestionResponse, status_code=status.HTTP_201_CREATED)
async def create(
    question: schema.QuestionCreate,
    db: Session = Depends(get_db)
):
    """
    创建新问题
    """
    try:
        return crud.create_question(db=db, question=question)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"创建问题失败: {str(e)}"
        )

@app.post("/bulk", response_model=List[schema.QuestionResponse], status_code=status.HTTP_201_CREATED)
async def create_bulk(
    questions: List[schema.QuestionCreate],
    db: Session = Depends(get_db)
):
    """
    批量创建问题
    """
    try:
        return crud.create_questions_bulk(db=db, questions=questions)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"批量创建问题失败: {str(e)}"
        )

@app.get("/", response_model=List[schema.QuestionResponse])
async def read_questions(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    course: Optional[str] = Query(None, description="按课程筛选"),
    major: Optional[str] = Query(None, description="按专业筛选"),
    subject: Optional[str] = Query(None, description="按科目筛选"),
    question_type: Optional[str] = Query(None, description="按问题类型筛选"),
    difficulty: Optional[int] = Query(None, ge=1, le=10, description="固定难度值"),
    difficulty_min: Optional[int] = Query(None, ge=1, le=10, description="最小难度"),
    difficulty_max: Optional[int] = Query(None, ge=1, le=10, description="最大难度"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    sort_by: str = Query("created_at", description="排序字段"),
    sort_order: str = Query("desc", description="排序方向: asc/desc"),
    db: Session = Depends(get_db)
):
    """
    获取问题列表，支持筛选、搜索和排序
    """
    try:
        questions = crud.get_questions(
            db=db,
            skip=skip,
            limit=limit,
            course=course,
            major=major,
            subject=subject,
            question_type=question_type,
            difficulty=difficulty,
            difficulty_min=difficulty_min,
            difficulty_max=difficulty_max,
            search=search,
            sort_by=sort_by,
            sort_order=sort_order
        )
        return questions
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取问题列表失败: {str(e)}"
        )

@app.get("/{question_id}", response_model=schema.QuestionResponse)
async def read_question(
    question_id: int = Path(..., ge=1, description="问题ID"),
    db: Session = Depends(get_db)
):
    """
    根据ID获取问题详情
    """
    question = crud.get_question(db=db, question_id=question_id)
    if question is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 ID {question_id} 不存在"
        )
    return question

@app.put("/{question_id}", response_model=schema.QuestionResponse)
async def update(
    question_update: schema.QuestionUpdate,
    question_id: int = Path(..., ge=1, description="问题ID"),
    db: Session = Depends(get_db)
):
    """
    更新问题信息
    """
    question = crud.update_question(db=db, question_id=question_id, question_update=question_update)
    if question is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 ID {question_id} 不存在"
        )
    return question

@app.patch("/{question_id}", response_model=schema.QuestionResponse)
async def partial_update(
    update_data: Dict[str, Any],
    question_id: int = Path(..., ge=1, description="问题ID"),
    db: Session = Depends(get_db)
):
    """
    部分更新问题字段
    """
    question = crud.partial_update_question(db=db, question_id=question_id, update_data=update_data)
    if question is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 ID {question_id} 不存在"
        )
    return question

@app.delete("/{question_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete(
    question_id: int = Path(..., ge=1, description="问题ID"),
    db: Session = Depends(get_db)
):
    """
    删除问题
    """
    success = crud.delete_question(db=db, question_id=question_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 ID {question_id} 不存在"
        )

@app.delete("/", status_code=status.HTTP_204_NO_CONTENT)
async def delete_bulk(
    question_ids: List[int] = Query(..., description="要删除的问题ID列表"),
    db: Session = Depends(get_db)
):
    """
    批量删除问题
    """
    deleted_count = crud.delete_questions_bulk(db=db, question_ids=question_ids)
    if deleted_count == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="没有找到要删除的问题"
        )

@app.get("/meta/courses", response_model=List[str])
async def get_courses_list(db: Session = Depends(get_db)):
    """
    获取所有课程列表
    """
    return crud.get_courses(db=db)

@app.get("/meta/majors", response_model=List[str])
async def get_majors_list(db: Session = Depends(get_db)):
    """
    获取所有专业列表
    """
    return crud.get_majors(db=db)

@app.get("/meta/subjects", response_model=List[str])
async def get_subjects_list(db: Session = Depends(get_db)):
    """
    获取所有科目列表
    """
    return crud.get_subjects(db=db)

@app.get("/meta/stats", response_model=Dict[str, Any])
async def get_questions_stats(db: Session = Depends(get_db)):
    """
    获取问题统计信息
    """
    return crud.get_question_stats(db=db)

@app.get("/count/total", response_model=int)
async def get_total_questions_count(
    course: Optional[str] = Query(None, description="按课程筛选"),
    major: Optional[str] = Query(None, description="按专业筛选"),
    subject: Optional[str] = Query(None, description="按科目筛选"),
    question_type: Optional[str] = Query(None, description="按问题类型筛选"),
    difficulty: Optional[int] = Query(None, ge=1, le=10, description="固定难度值"),
    difficulty_min: Optional[int] = Query(None, ge=1, le=10, description="最小难度"),
    difficulty_max: Optional[int] = Query(None, ge=1, le=10, description="最大难度"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """
    获取问题总数（用于分页）
    """
    return crud.get_questions_count(
        db=db,
        course=course,
        major=major,
        subject=subject,
        question_type=question_type,
        difficulty=difficulty,
        difficulty_min=difficulty_min,
        difficulty_max=difficulty_max,
        search=search
    )

@app.get("/check/{question_id}", response_model=bool)
async def check_question_exists(
    question_id: int = Path(..., ge=1, description="问题ID"),
    db: Session = Depends(get_db)
):
    """
    检查问题是否存在
    """
    return crud.question_exists(db=db, question_id=question_id)